import {Component, OnInit} from '@angular/core';
import {OperateService} from '../../operate.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ActivatedRoute} from '@angular/router';
import {NzUploadFile} from 'ng-zorro-antd/upload';

@Component({
  selector: 'app-edit-goods',
  templateUrl: './edit-goods.component.html',
  styleUrls: ['./edit-goods.component.scss']
})
export class EditGoodsComponent implements OnInit {
  formData: any = {
    id: '',
    name: '', // 商品名称
    type: 2, // 商品分类：1-实物、2-虚拟
    price: '', // 商品价格
    integral: '', // 兑换积分
    stock: '', // 库存
    salesVolumeBase: '', // 虚拟叠加兑换数量
    sort: '', // 排序
    icon: '', // 商品主图
    imgs: [], // 商品列表图
    introduction: [], // 商品详情图
    codes: [], // 兑换码
    vipLevel: '', // 兑换码
  };
  codeFile: any;
  codeListModal = {
    visible: false,
    query: {
      state: '',
      page: 1,
      pageSize: 10,
    },
    table: {
      records: [],
      total: 0,
    }
  };
  beforeUpload = (file: NzUploadFile): boolean => {
    const fileName: any = file.name.split('.').pop();
    if (fileName !== 'txt') {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    const reader: any = new FileReader();
    reader.readAsText(file, 'utf-8');
    reader.onload = () => {
      const result = reader.result.replace(/\r/g, '');
      if (!result) {
        this.nzMessageService.error(`没有读取到数据`);
        return;
      }
      this.formData.codes = Array.from(new Set([...result.split('\n').filter((v: any) => v !== ''), ...this.formData.codes]));
      this.nzMessageService.success(`已读取${this.formData.codes.length}条`);
    };
    reader.onerror = () => {
      this.nzMessageService.error('读取失败');
      console.log(reader.error);
    };
    return false;
  };

  constructor(
    private operateService: OperateService,
    private nzMessageService: NzMessageService,
    private activatedRoute: ActivatedRoute
  ) {
  }

  ngOnInit(): void {
    let detail = this.activatedRoute.snapshot.queryParams.goodsDetail;
    if (detail) {
      detail = JSON.parse(detail);
      this.formData = {
        id: detail.id,
        name: detail.name,
        type: detail.type,
        price: detail.price,
        integral: detail.integral,
        stock: detail.stock,
        salesVolumeBase: detail.salesVolumeBase,
        vipLevel: detail.vipLevel,
        codes: JSON.parse(detail.codes) || [],
        sort: detail.sort,
        icon: detail.icon,
        imgs: detail.imgs.split(','),
        introduction: detail.introduction.split(','),
      };
    }
  }

  // 移除图片
  removeImg(index: any, key: string) {
    this.formData[key].splice(index, 1);
  }

  // 添加图片
  appendImg(url: any, key: string) {
    this.formData[key].push(url);
  }

  submit() {
    if (!this.formData.name.trim()) {
      this.nzMessageService.error('请输入商品名称');
      return;
    }
    if (!this.formData.name.trim()) {
      this.nzMessageService.error('请输入商品价格');
      return;
    }
    if (!this.formData.name.trim()) {
      this.nzMessageService.error('请输入兑换积分');
      return;
    }
    if (!this.formData.name.trim()) {
      this.nzMessageService.error('请输入排序');
      return;
    }
    if (this.formData.type !== 3 && !this.formData.name.trim()) {
      this.nzMessageService.error('请输入库存');
      return;
    }
    if (!this.formData.name.trim()) {
      this.nzMessageService.error('请输入虚拟叠加兑换数量');
      return;
    }
    if (this.formData.vipLevel === '') {
      this.nzMessageService.error('请选择兑换限制');
      return;
    }
    if (!this.formData.icon) {
      this.nzMessageService.error('请选择商品主图');
      return;
    }
    if (!this.formData.imgs.length) {
      this.nzMessageService.error('请选择商品列表图');
      return;
    }
    if (!this.formData.introduction.length) {
      this.nzMessageService.error('请选择商品详情图');
      return;
    }
    this.operateService.addAndModifyGoods({
      ...this.formData,
      imgs: this.formData.imgs.join(','),
      codes: this.formData.codes.join(','),
      stock: this.formData.type !== 3 ? this.formData.stock : '',
      introduction: this.formData.introduction.join(','),
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        window.history.back();
      }
    });
  }

  showCodeList() {
    this.getCodeList();
    this.codeListModal.visible = true;
  }

  hideCodeList() {
    this.codeListModal = {
      visible: false,
      query: {
        state: '',
        page: 1,
        pageSize: 10,
      },
      table: {
        records: [],
        total: 0,
      }
    };
  }

  onPageIndexChange(index: number) {
    this.codeListModal.query.page = index;
    this.getCodeList();
  }

  onPageSizeChange(pageSize: number) {
    this.codeListModal.query.pageSize = pageSize;
    this.getCodeList();
  }

  queryBtn() {
    this.codeListModal.query.page = 1;
    this.getCodeList();
  }

  getCodeList() {
    this.operateService.getCode({
      goodsId: this.formData.id,
      state: this.codeListModal.query.state,
      page: this.codeListModal.query.page,
      pageSize: this.codeListModal.query.pageSize,
    }).then((res: any) => {
      if (res.code === 0) {
        this.codeListModal.table = res.data;
      }
    });
  }

  deleteCode(id: any) {
    this.operateService.deleteCode({
      id,
      state: 2,
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('删除成功');
        this.getCodeList();
      }
    });
  }
}
